package com.zyw.customcalendar.operation;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.TimeZone;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.os.Looper;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.zyw.customcalendar.AppApplication;
import com.zyw.customcalendar.model.RealWeather;
import org.json.JSONException;
import org.json.JSONObject;

public class WeartherManager {

    private Gson mGson;
    private OkHttpClient mOkClient;
    private static WeartherManager mWeaManager;
    
    public static final String REAL_WEARTHER_URL = 
            "http://v.juhe.cn/weather/index";

    private Handler mHandler;

    private static final String JU_KEY = "1054befc9dde0a815264079ca2b9c4d4";
    
    public WeartherManager() {
        // TODO Auto-generated constructor stub
        
        mGson = new Gson();
        
        mOkClient = new OkHttpClient();

        mHandler = new Handler(Looper.getMainLooper());
    }

    public static WeartherManager getInstance(){
        if(mWeaManager == null){
            synchronized(WeartherManager.class){
                if(mWeaManager == null){
                    mWeaManager = new WeartherManager();
                }
            }
        }
        return mWeaManager;
    }
    
    public void getRealWearther(final WeatherCallback weaCallback, String cityName){
        //先检查本地数据
        String weatherString = (String)AppApplication.getInstance().getSharePreferencesValue(cityName+"_weather", "");
        if(weatherString != null && !"".equals(weatherString)) {
            RealWeather realWeather = mGson.fromJson(weatherString, RealWeather.class);
            if(getCurrentYMD().equals(realWeather.date_y)){
                weaCallback.onSuccess(realWeather);
                AppApplication.getInstance().saveSharePreferences("city_name", realWeather.city);
                return;
            }
        }
        try {
            cityName = URLEncoder.encode(cityName, "utf-8");
            String url = REAL_WEARTHER_URL + "?format=2&cityname=" + cityName + "&key="+JU_KEY;

            Request request = new Request.Builder().url(url).build();
            Call call = mOkClient.newCall(request);
            call.enqueue(new Callback(){

                @Override
                public void onFailure(Call arg0, IOException arg1) {
                    // TODO Auto-generated method stub
                    weaCallback.onFailure(arg1.getMessage());
                }

                @Override
                public void onResponse(Call arg0, Response response) throws IOException {
                    // TODO Auto-generated method stub
                    String resultString = response.body().string();
                    if(resultString != null){
                        JSONObject jb;
                        try {
                            jb = new JSONObject(resultString);
                            String resultCode = jb.optString("resultcode");
                            if(!"200".equals(resultCode)) {
                                return;
                            }

                            JSONObject resultObj = jb.optJSONObject("result");
                            String realWeaString = resultObj.getString("today");
                            final RealWeather realWeather = mGson.fromJson(realWeaString, RealWeather.class);
                            if(realWeather != null){
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Log.i("zyw", "object=" + realWeather.date_y);
                                        weaCallback.onSuccess(realWeather);
                                    }
                                });
                            }
                            //保存天气数据
                            AppApplication.getInstance().saveSharePreferences(realWeather.city+"_weather", realWeaString);
                            AppApplication.getInstance().saveSharePreferences("city_name", realWeather.city);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                }

            });
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private String getCurrentYMD(){
        Calendar currentCalendar = Calendar.getInstance();
        currentCalendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        int year = currentCalendar.get(Calendar.YEAR);
        int months = currentCalendar.get(Calendar.MONTH) + 1;
        int day = currentCalendar.get(Calendar.DAY_OF_MONTH);

        String days = year + "";
        if(months < 10)
            days += "年0" + months;
        else{
            days +=  "年" + months;
        }

        if(day < 10)
            days += "月0" + day + "日";
        else
            days += "月" + day + "日";
        android.util.Log.i("zyw","days="+days);
        return days;
    }
    
    public interface WeatherCallback{
        
        public void onSuccess(Object object);
        
        public void onFailure(Object object);
    }
}
